# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\PyInstaller\utils\misc.py
"""
This module is for the miscellaneous routines which do not fit somewhere else.
"""
import glob, os, pprint, py_compile, sys
from PyInstaller import log as logging
from PyInstaller.compat import BYTECODE_MAGIC, is_py2

logger = logging.getLogger(__name__)


def dlls_in_subdirs(directory):
    """Returns a list *.dll, *.so, *.dylib in given directories and subdirectories."""
    filelist = []
    for root, dirs, files in os.walk(directory):
        filelist.extend(dlls_in_dir(root))

    return filelist


def dlls_in_dir(directory):
    """Returns a list of *.dll, *.so, *.dylib in given directory."""
    return files_in_dir(directory, ["*.so", "*.dll", "*.dylib"])


def files_in_dir(directory, file_patterns=[]):
    """Returns a list of files which match a pattern in given directory."""
    files = []
    for file_pattern in file_patterns:
        files.extend(glob.glob(os.path.join(directory, file_pattern)))

    return files


def get_unicode_modules():
    """
    Try importing codecs and encodings to include unicode support
    in created binary.
    """
    modules = []
    try:
        import codecs

        modules.append("codecs")
    except ImportError:
        logger.error("Cannot detect modules 'codecs'.")

    return modules


def get_path_to_toplevel_modules(filename):
    """
    Return the path to top-level directory that contains Python modules.
    
    It will look in parent directories for __init__.py files. The first parent
    directory without __init__.py is the top-level directory.
    
    Returned directory might be used to extend the PYTHONPATH.
    """
    curr_dir = os.path.dirname(os.path.abspath(filename))
    pattern = "__init__.py"
    try:
        for i in range(10):
            files = set(os.listdir(curr_dir))
            if pattern in files:
                curr_dir = os.path.dirname(curr_dir)
            else:
                return curr_dir

    except IOError:
        pass


def mtime(fnm):
    try:
        return os.stat(fnm)[8]
    except:
        return 0


def compile_py_files(toc, workpath):
    """
    Given a TOC or equivalent list of tuples, generates all the required
    pyc/pyo files, writing in a local directory if required, and returns the
    list of tuples with the updated pathnames.
    
    In the old system using ImpTracker, the generated TOC of "pure" modules
    already contains paths to nm.pyc or nm.pyo and it is only necessary
    to check that these files are not older than the source.
    In the new system using ModuleGraph, the path given is to nm.py
    and we do not know if nm.pyc/.pyo exists. The following logic works
    with both (so if at some time modulegraph starts returning filenames
    of .pyc, it will cope).
    """
    basepath = os.path.join(workpath, "localpycos")
    new_toc = []
    for nm, fnm, typ in toc:
        if typ != "PYMODULE":
            new_toc.append((nm, fnm, typ))
            continue
            if fnm.endswith(".py"):
                src_fnm = fnm
                obj_fnm = src_fnm + ("o" if sys.flags.optimize else "c")
                if not os.path.exists(obj_fnm):
                    obj_fnm = src_fnm + ("c" if sys.flags.optimize else "o")
                else:
                    obj_fnm = fnm
                    src_fnm = fnm[:-1]
            needs_compile = (
                mtime(src_fnm) > mtime(obj_fnm)
                or open(obj_fnm, "rb").read()[:4] != BYTECODE_MAGIC
            )
        if needs_compile:
            try:
                py_compile.compile(src_fnm, obj_fnm)
                logger.debug("compiled %s", src_fnm)
            except IOError:
                ext = os.path.splitext(obj_fnm)[1]
                if "__init__" not in obj_fnm:
                    leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1]
                else:
                    leading, mod_name = nm.split("."), "__init__"
                leading = os.path.join(basepath, *leading)
                if not os.path.exists(leading):
                    os.makedirs(leading)
                obj_fnm = os.path.join(leading, mod_name + ext)
                needs_compile = (
                    mtime(src_fnm) > mtime(obj_fnm)
                    or open(obj_fnm, "rb").read()[:4] != BYTECODE_MAGIC
                )
                if needs_compile:
                    py_compile.compile(src_fnm, obj_fnm)
                    logger.debug("compiled %s", src_fnm)

            new_toc.append((nm, obj_fnm, typ))

    return new_toc


def save_py_data_struct(filename, data):
    """
    Save data into text file as Python data structure.
    :param filename:
    :param data:
    :return:
    """
    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    if is_py2:
        import codecs

        f = codecs.open(filename, "w", encoding="utf-8")
    else:
        f = open(filename, "w", encoding="utf-8")
    with f:
        pprint.pprint(data, f)


def load_py_data_struct(filename):
    """
    Load data saved as python code and interpret that code.
    :param filename:
    :return:
    """
    if is_py2:
        import codecs

        f = codecs.open(filename, "rU", encoding="utf-8")
    else:
        f = open(filename, "rU", encoding="utf-8")
    with f:
        from ..depend.bindepend import BindingRedirect

        return eval(f.read())


def absnormpath(apath):
    return os.path.abspath(os.path.normpath(apath))


def module_parent_packages(full_modname):
    """
    Return list of parent package names.
        'aaa.bb.c.dddd' ->  ['aaa', 'aaa.bb', 'aaa.bb.c']
    :param full_modname: Full name of a module.
    :return: List of parent module names.
    """
    prefix = ""
    parents = []
    for pkg in full_modname.split(".")[0:-1]:
        prefix += "." + pkg if prefix else pkg
        parents.append(prefix)

    return parents
